﻿using System.Collections.Generic;
using System.Linq;

namespace Common.Infrastructure.Structs
{
    public class LibMessageFormat
    {
        private readonly List<LibMessageFormatInfo> formatInfos;

        public LibMessageFormat()
        {
            formatInfos = new List<LibMessageFormatInfo>();
        }

        public string Code { get; set; }

        public void AddFormat(string lang, string format)
        {
            if (string.IsNullOrEmpty(format))
            {
                return;
            }

            var f = formatInfos.FirstOrDefault(t => string.Compare(t.Lang, lang, true) == 0);
            if (f != null)
            {
                formatInfos.Remove(f);
            }

            var info = new LibMessageFormatInfo()
            {
                Lang = lang,
                Format = format,
            };
            formatInfos.Add(info);
        }

        public string GetFormat(string lang)
        {
            if (string.IsNullOrEmpty(lang))
            {
                var r = formatInfos.FirstOrDefault(t => string.IsNullOrEmpty(t.Lang));
                if (r != null)
                {
                    return r.Format;
                }

                r = formatInfos.FirstOrDefault();
                if (r != null)
                {
                    return r.Format;
                }
            }

            var f = formatInfos.FirstOrDefault(t => string.Compare(t.Lang, lang, true) == 0);
            if (f != null)
            {
                return f.Format;
            }

            if (formatInfos.Any())
            {
                var r = formatInfos.FirstOrDefault();
                if (r != null)
                {
                    return r.Format;
                }
            }

            return null;
        }
    }
}
